package com.hlkt.adapter.abs;

import java.util.List;

import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import com.hlkt.adapter.AdapterItem;

/**
 * @author dson
 * @date 2015-11-09
 */
public abstract class CommonAdapter<T> extends BaseAdapter {

	private List<T> mDataList;
	private LayoutInflater mInflater;

	protected CommonAdapter(@NonNull List<T> data) {
		mDataList = data;
	}

	@Override
	public int getCount() {
		return mDataList.size();
	}

	@Override
	public T getItem(int position) {
		return mDataList.get(position);
	}

	/**
	 * 替换listView中的数据源
	 */
	public void updateData(List<T> data) {
		mDataList = data;
		notifyDataSetChanged();
	}

	/**
	 * 批量添加记录
	 * 
	 * @param moreData
	 */
	public void addItems(List<T> moreData) {
		mDataList.addAll(moreData);
		notifyDataSetChanged();
	}

	public List<T> getDataList() {
		return mDataList;
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	/**
	 * instead by{@link #getItemViewType(Object)}
	 * 
	 * @Override
	 * @Deprecated public int getItemViewType(int position) { mType =
	 *             getItemViewType(mDataList.get(position)); // Log.d("ddd",
	 *             "getType = " + util.getIntType(mType)); //
	 *             如果不写这个方法，会让listView更换dataList后无法刷新数据 return
	 *             util.getIntType(mType); }
	 */

	public Object getItemViewType(T t) {
		return t;
	}

	@SuppressWarnings("unchecked")
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// Log.d("ddd", "getView");
		if (mInflater == null) {
			mInflater = LayoutInflater.from(parent.getContext());
		}

		AdapterItem<T> item;
		if (convertView == null) {
			item = getItemView();
			convertView = mInflater.inflate(item.getLayoutResId(), parent,
					false);
			convertView.setTag(item);
			item.onBindViews(convertView);
			item.onSetViews();
		} else {
			item = (AdapterItem<T>) convertView.getTag();
		}
		item.onUpdateViews(mDataList.get(position), position);
		return convertView;
	}

	public abstract @NonNull
	AdapterItem<T> getItemView();

}
